package com.chase.springboot.controller;

import com.chase.springboot.service.IQiniuService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/qiniu")
public class QiniuController {

    @Autowired
    IQiniuService qiniuService;


    /**
     * 上传图片文件七牛云
     * @param files
     * @return
     */
    @PostMapping(value="/upload")
    public String uploadImg(@RequestParam("file") MultipartFile files) throws IOException {
        String url = qiniuService.uploadFile(files.getInputStream(),files.getOriginalFilename());
        return new Gson().toJson(url);
    }

    @PostMapping("/uploadLocal")
    public String uploadLocal(@RequestParam MultipartFile file, HttpServletRequest request){
        if (file == null) return "文件为空！";
        String uploadPath = "D:\\appdata\\java\\uploadFile";
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        String OriginalFilename = file.getOriginalFilename();     //获取原文件名
        String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf(".")); //获取文件后缀名
        //重新随机生成名字
        String filename = UUID.randomUUID().toString() +suffixName;
        File localFile = new File(uploadPath+"\\"+filename);
        try {
            file.transferTo(localFile); //把上传的文件保存至本地
            /**
             * 这里应该把filename保存到数据库,供前端访问时使用
             */
        }catch (IOException e){
            e.printStackTrace();
        }
        return filename;
    }

}
